package com.yang.serialport.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yang.serialport.tools.HTTPTools;
import com.yang.serialport.ui.MainFrame;

public class DataClient {

    public String getServerCmd() {

        String url = Address.HOST_ADDRESS + "/api/beike/express/shelf/light/getCmd";
        String response = HTTPTools.getResponseBody(url, null, true);
        JSONObject object;
        try {
            object = JSON.parseObject(response);
            return object.getString("data");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public void startRequestLoop(final MainFrame mainFrame) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (mainFrame.isInitFinished()) {
                        if (!mainFrame.isSreialPortOpened()) {
                            mainFrame.setTitle("串口通信(等待串口打开...)");
                            mainFrame.openSreialPort();

                        } else {
                            if (mainFrame.isDataAvailable()) {
                                mainFrame.setTitle("串口通信(接收数据...)");
                                String cmd = getServerCmd();
                                if (cmd != null && cmd.length() != 0) {
                                    mainFrame.sendCmd(cmd, true);
                                }
                            } else {
                                mainFrame.setTitle("串口通信(等待串口数据返回...)");
                            }
                        }
                    } else {
                        mainFrame.setTitle("串口通信(等待窗口初始化...)");
                    }
                    sleep();
                }
            }
        });
        thread.start();
    }

    public static void sleep() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void initDataClient(MainFrame mainFrame) {
        DataClient client = new DataClient();
        client.startRequestLoop(mainFrame);
    }

}
